package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.utils.DateUtils;
import com.sangmo.boot.framework.data.idm.IdentityManager;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.service.CompanyService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.storage.interfaces.CsfLoanCreation;
import com.sangmo.fts.process.storage.model.CsfAgreement;
import com.sangmo.fts.process.storage.model.CsfContract;
import com.sangmo.fts.process.storage.model.CsfLoan;
import com.sangmo.fts.process.storage.repo.CsfLoanRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class CsfLoanEntityService  extends AuthorityEntityService<CsfLoan> {

    @Autowired
    private CsfLoanRepo csfLoanRepo;

    @Autowired
    private IdentityManager identityManager;

    @Autowired
    private CsfContractService csfContractService;

    @Autowired
    private CsfAgreementService csfAgreementService;

    @Autowired
    private CompanyService companyService;


    @Override
    protected IDataViewRepo<CsfLoan> getRepo() {
        return csfLoanRepo;
    }

    @Override
    protected void onCreate(CsfLoan entity, Object bo) {
        super.onCreate(entity, bo);
        entity.setApplyCode(DateUtils.format(new Date(), "yyyyMMdd") + identityManager.next("CSF_LOAN", 5));

        CsfLoanCreation creation = (CsfLoanCreation) bo;
        CsfContract contract = csfContractService.get(creation.getContractId());
        entity.setApplyId(contract.getBuyerId());
        CsfAgreement agreement = csfAgreementService.findByContractId(contract.getId());
        entity.setAgreementId(agreement.getId());
        entity.setBankId(agreement.getBankId());
    }
}
